const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ObjectId = Schema.ObjectId

const CommentSchema = new Schema({
    article_id: {
        type: ObjectId,
        ref: 'Article'
    },
    content: String,
    create_time: {
        type: Date,
        default: Date.now()
    },
    update_time: {
        type: Date
    },
    state: {
        type: Number,
        default: 0 // 状态 0待审核/1通过正常/-2垃圾评论
    },
    position: {
        type: String
    },
    likes: {
        type: Number,
        default: 0
    },
    is_top: {
        type: Boolean,
        default: false
    },
    name: {
        type: String,
        validate: /\S+/,
        require: true
    },
    email: {
        type: String,
        validate: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/
    },
    site: {
        type: String,
        validate: /^((https|http):\/\/)+[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/
    }
})

// 更新修改时间
CommentSchema.pre('save', function(next) {
    if (this.isNew) {
        this.update_time = this.create_time = Date.now()
    } else {
        this.update_time = Date.now()
    }
    next()
})
CommentSchema.pre('findOneAndUpdate', function(next) {
    this.findOneAndUpdate({}, {
        update_time: Date.now()
    })
    next()
})

mongoose.model('Comment', CommentSchema)